package com.ridaizu.bean;

import java.io.Serializable;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;

import com.google.common.base.Strings;
import com.ridaizu.cache.CacheDataBean;
import com.ridaizu.dao.db.DBManager;
import com.ridaizu.lazy.LazyTransitDataModel;
import com.ridaizu.model.Transit;
import com.ridaizu.model.form.TransitForm;
import com.ridaizu.model.search.TransitSearch;
import com.ridaizu.service.impl.TransitServiceImpl;
import com.ridaizu.util.DateUtil;

@javax.faces.bean.ManagedBean(name = "transitBean")
@SessionScoped
public class TransitBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private LazyDataModel<Transit> lazyModel;

    @ManagedProperty("#{cacheDataBean}")
    private CacheDataBean cacheDataBean;

    @ManagedProperty("#{transitServiceImpl}")
    private TransitServiceImpl transitService;

    @ManagedProperty("#{transitSearch}")
    private TransitSearch transitSearch;

    @ManagedProperty("#{transitForm}")
    private TransitForm transitForm;

	public void searchTransitSync() {
		lazyModel = new LazyTransitDataModel(transitSearch);
	}

	public void viewRegisterTransit() throws SQLException {

		setInitValues(null);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 200);

        RequestContext.getCurrentInstance().openDialog("transit", options, null);
    }

	public void viewUpdateTransit(Transit transit) throws SQLException {

		setInitValues(transit);

        Map<String,Object> options = new HashMap<String, Object>();
        options.put("modal", true);
        options.put("contentWidth", 550);
        options.put("contentHeight", 220);

        RequestContext.getCurrentInstance().openDialog("transit", options, null);
    }

	private void setInitValues(Transit transit) throws SQLException {
		transitForm.clearAll();
		setValues(transit);
	}

	private void setValues(Transit transit) {
		if (transit == null) {
			setRegisterValues();
		} else {
			setUpdateValues(transit);
		}
	}

	private void setRegisterValues() {
	}

	private void setUpdateValues(Transit transit) {
		transitForm.setId(String.valueOf(transit.getId()));
		transitForm.setTransitDate(transit.getTransitDate());
		transitForm.setGoodsTotalCount(String.valueOf(transit.getGoodsTotalCount()));
		transitForm.setGoodsTotalPrice(String.valueOf(transit.getGoodsTotalPrice()));
		transitForm.setFreightTotal(String.valueOf(transit.getFreightTotal()));
		transitForm.setArriveFlg(transit.isArriveFlg());
		transitForm.setArriveDate(transit.getArriveDate());

	}

	public void registerTransit() {
		Transit transit = getTransit();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = transitService.insertModel(transit);
			DBManager.commitTransaction();

		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
    }

	public void updateTransit() {

		Transit transit = getTransit();

		boolean result = false;

		try {
			DBManager.beginTransaction();
			result = transitService.updateModel(transit);
			DBManager.commitTransaction();

		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		RequestContext.getCurrentInstance().closeDialog(result);
	}

	public void deleteTransit() {

		Transit selectedTransit = transitForm.getSelectedTransit() ;

		if (selectedTransit == null || selectedTransit.getId() < 1) {
	        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", "请选择要删除的在途信息。");
	        FacesContext.getCurrentInstance().addMessage(null, message);

	        return ;
		}

		boolean result = false;
		try {
			DBManager.beginTransaction();
			result = transitService.deleteModel(selectedTransit.getId());
			DBManager.commitTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
			result = false;
			DBManager.rollbackTransaction();
		}

		String resultStr = null;
		if (result) {
			resultStr = String.format("在途[%s]删除成功。", selectedTransit.getId());
		} else {
			resultStr = String.format("在途[%s]删除失败。", selectedTransit.getId());
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Transit delete result", resultStr);
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void registerTransitResult(SelectEvent event) {
		boolean result = (Boolean) event.getObject();

		handleResult(result, "登录");
	}

	public void updateTransitResult(SelectEvent event) {

		boolean result = (Boolean) event.getObject();

		handleResult(result, "更新");
	}

	private void handleResult(boolean result, String optStr) {

		String resultStr = null;
		if (result) {
			resultStr = String.format("在途信息%s成功。", optStr);
		} else {
			resultStr = String.format("在途信息%s失败。", optStr);;
		}

        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message", resultStr);

        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	private Transit getTransit() {

		Transit transit = new Transit();

		if (!Strings.isNullOrEmpty(transitForm.getId())) {
			transit.setId(Integer.valueOf(transitForm.getId()));
		}

		if (transitForm.getTransitDate() != null) {
			transit.setTransitDate(new Timestamp(transitForm.getTransitDate().getTime()));
		}

		if (!Strings.isNullOrEmpty(transitForm.getGoodsTotalCount())) {
			transit.setGoodsTotalCount(Integer.valueOf(transitForm.getGoodsTotalCount()));
		}


		if (!Strings.isNullOrEmpty(transitForm.getGoodsTotalPrice())) {
			transit.setGoodsTotalPrice(Double.valueOf(transitForm.getGoodsTotalPrice()));
		}

		if (!Strings.isNullOrEmpty(transitForm.getFreightTotal())) {
			transit.setFreightTotal(Double.valueOf(transitForm.getFreightTotal()));
		}

		transit.setArriveFlg(transitForm.isArriveFlg());

		if (transitForm.getArriveDate() != null) {
			transit.setArriveDate(new Timestamp(transitForm.getArriveDate().getTime()));
		}

		Timestamp currentDate = DateUtil.getCurrentDateTime();

		transit.setRgtOpt("Admin");
		transit.setRgtDate(currentDate);
		transit.setUpdOpt("Admin");
		transit.setUpdDate(currentDate);

		return transit;
	}

	public LazyDataModel<Transit> getLazyModel() {
		return lazyModel;
	}

	public void setLazyModel(LazyDataModel<Transit> lazyModel) {
		this.lazyModel = lazyModel;
	}

	public TransitServiceImpl getTransitService() {
		return transitService;
	}

	public void setTransitService(TransitServiceImpl transitService) {
		this.transitService = transitService;
	}

	public TransitSearch getTransitSearch() {
		return transitSearch;
	}

	public void setTransitSearch(TransitSearch transitSearch) {
		this.transitSearch = transitSearch;
	}

	public TransitForm getTransitForm() {
		return transitForm;
	}

	public void setTransitForm(TransitForm transitForm) {
		this.transitForm = transitForm;
	}

	public CacheDataBean getCacheDataBean() {
		return cacheDataBean;
	}

	public void setCacheDataBean(CacheDataBean cacheDataBean) {
		this.cacheDataBean = cacheDataBean;
	}

}